<?php
class User {
	var $DB;
	function User($DB) {
		$this->DB = $DB;
		$this->tblName =  "admin";
	} 

	function Logins ($username, $password) {
		$sql = "SELECT * from {$this->tblName} WHERE adminuser  = '$username' ";
		$this->DB->query($sql);
		$record = $this->DB->fetchRow();
		if (!$record) {
			return false;
		} else {
			$check_pwd = md5($password);
			if ($record['password'] == $check_pwd) {
				global $onlineip;
				$timestamp = time();
				$this->DB->query("UPDATE {$this->tblName} SET loginip = '$onlineip',logintime='$timestamp',loginnum = loginnum+1 WHERE adminuser = '$username'"); 
				// 登录成功
				session_start();
				$_SESSION['adminuser'] = $username;
				$_SESSION['uid'] = $record['id'];
				$_SESSION['isLogin'] = true;
				return true;
			} else {
				// de("2出错");
				return false;
			} 
		} 
	} 
	function addUser($name, $pwd, $groupid) {
		$sql = "SELECT id FROM {$this->tblName} WHERE name = '$name'";
		$this->DB->query($sql);
		if ($this->DB->recordCount()) {
			return -1;
		} 
		$sql = "INSERT INTO {$this->tblName} VALUES('','$name',MD5('$pwd'),'$groupid')";
		$this->DB->query($sql);
		return $this->DB->insertID();
	} 
	// 从数据库中删除一个帐户
	function delUser($id) {
		return $this->delete($id);
	} 
	// 修改帐户
	function editUser($id, $pwd, $groupid) {
		$sql = "UPDATE {$this->tblName}
				SET pwd	= MD5('$pwd'),groupid='$groupid' 
				WHERE id = '$id'";
		if ($this->DB->query($sql))
			return true;
		else
			return false;
	} 
	// 取得一个帐户记录
	function getUser($id) {
		$sql = "SELECT id, name,groupid FROM {$this->tblName}
				WHERE id = '$id'";
		$this->DB->query($sql);
		return $this->DB->fetchRow();
	} 
	// 取得帐户列表
	function listUser() {
		$sql = "SELECT id, name AS userName FROM {$this->tblName}";
		$this->DB->query($sql);
		if ($this->DB->recordCount())
			return $this->DB->fetchAll();
		else
			return 0;
	} 
	// 帐户修改密码
	function setPwd($id, $oriPwd, $newPwd) {
		$sql = "SELECT id FROM {$this->tblName}
				WHERE pwd = MD5('$oriPwd')";
		$this->DB->query($sql);
		if ($this->DB->recordCount() == 0)
			return 2;
		$sql = "UPDATE {$this->tblName}
				SET pwd = MD5('$newPwd')
				WHERE id = '$id'";
		if ($this->DB->query($sql))
			return true;
		else
			return false;
	} 
} 

?>
